package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/exec"
	"strconv"
	"strings"

	"github.com/devfeel/dotweb"
)

func main() {
	//初始化DotServer
	app := dotweb.New()

	//设置dotserver日志目录
	//如果不设置，默认不启用，且默认为当前目录
	app.SetEnabledLog(true)
	app.SetLogPath("./log")

	//开启development模式
	app.SetDevelopmentMode()

	//设置gzip开关
	//app.HttpServer.SetEnabledGzip(true)

	//设置Session开关
	//app.HttpServer.SetEnabledSession(true)

	//设置Session配置
	//app.HttpServer.SetSessionConfig(session.NewDefaultRuntimeConfig())

	//设置静态文件
	app.HttpServer.ServerFile("/image/*filepath", "./image")
	app.HttpServer.ServerFile("/assets/css/*filepath", "./views/assets/css")
	app.HttpServer.ServerFile("/assets/fonts/*filepath", "./views/assets/fonts")
	app.HttpServer.ServerFile("/assets/js/*filepath", "./views/assets/js")
	app.HttpServer.ServerFile("/assets/i/*filepath", "./views/assets/i")
	app.HttpServer.Renderer().SetTemplatePath("./views/")
	//设置路由
	app.HttpServer.GET("/", index)
	app.HttpServer.POST("/startrobot", startRobot)
	app.HttpServer.POST("/showlog", showRobotLog)
	//自定义404输出
	app.SetNotFoundHandle(func(c dotweb.Context) {
		c.Response().WriteHeader(http.StatusNotFound)
		msg := []byte("is't app's not found!")
		c.Response().Write(len(msg), msg)
	})

	// 开始服务
	port := 9999
	fmt.Println("dotweb.StartServer => " + strconv.Itoa(port))
	err := app.StartServer(port)
	fmt.Println("dotweb.StartServer error => ", err)
}

func index(ctx dotweb.Context) error {
	err := ctx.View("index.html")
	return err
}

type GobalConfig struct {
	ProxyIP   string `json:"proxyIP"`
	ProxyPort int    `json:"proxyPort"`
	ZoneId    uint32 `json:"zoneId"`
}
type RobotConfig struct {
	Accid       uint64  `json:accid`
	LogicModule []int32 `json:logicModule`
}
type RoRobotConfig struct {
	Global GobalConfig   `json:global`
	Robots []RobotConfig `json:robots`
}

func startRobot(ctx dotweb.Context) error {

	//将json字符串解析出来
	config := RoRobotConfig{}
	err := json.Unmarshal(ctx.Request().PostBody(), &config)
	if err != nil {
		ctx.WriteStringC(500, "json解析错误,请检查")
		return err
	}
	fmt.Printf("%v\n", config)
	//返回消息
	ctx.WriteStringC(200, "json解析成功,开始执行")
	//执行
	go runRoRobot(ctx.Request().PostBody())

	return nil
}

func prepareRun(jsonBytes []byte) error {
	//删除之前日志,配置文件
	os.Remove("./tools/RoRobot.log")
	os.Remove("./tools/RoRobotConfig.json")
	//将新的配置文件写入
	return ioutil.WriteFile("./tools/RoRobotConfig.json", jsonBytes, 0666)
}

func runRoRobot(jsonByte []byte) {
	//删除旧配置,日志
	err := prepareRun(jsonByte)
	if err != nil {
		return
	}
	fmt.Println("执行RoRobot")
	// cmd := exec.Command("pwd")
	// b, _ := cmd.Output()
	// fmt.Println(string(b))
	cmd := exec.Command("sh", "startRobot.sh")
	fmt.Println(cmd.Env)
	fmt.Println(cmd.Dir)
	fmt.Println(cmd.Output())
}

func parsePostContent(content string) map[string]string {
	//start=10;
	params := make(map[string]string)
	list := strings.Split(content, ";")
	for i := 0; i < len(list); i++ {
		cell := strings.Split(list[i], "=")
		params[cell[0]] = cell[1]
	}
	return params
}

func showRobotLog(ctx dotweb.Context) error {
	//解析参数
	content := ctx.Request().PostBody()
	params := parsePostContent(string(content))
	tmp, ok := params["start"]
	if !ok {
		ctx.Response().Write(417, []byte("缺少start参数"))
		return nil
	}
	start, err := strconv.Atoi(tmp)
	if err != nil {
		log.Println(err)
		return err
	}
	//打开文件
	fileFd, err := os.OpenFile("./tools/RoRobot.log", os.O_RDONLY, 0666)
	defer fileFd.Close()
	if err != nil {
		log.Println(err)
	}
	//偏移
	fileInfo, err := os.Stat("./tools/RoRobot.log")
	if err != nil {
		log.Println(err)
	}
	if fileInfo.Size() < int64(start) {
		ctx.Response().Write(417, []byte("参数过大,超过日志大小"))
		return nil
	}
	fileFd.Seek(int64(start), 1)
	//读取新增内容
	addstr, err := ioutil.ReadAll(fileFd)
	if err != nil {
		log.Println(err)
		return err
	}
	ctx.Response().SetHeader("logsize", strconv.Itoa(len(addstr)))
	num, err := ctx.Response().Write(200, addstr)
	log.Printf("log 日志字节 = %d 发送字节 = %d", len(content), num)

	return err
}
